package com.github.baichuan.application.scaffold.controller;

import com.github.baichuan.application.scaffold.domain.application.Realm;
import com.github.baichuan.application.scaffold.domain.application.RealmService;
import com.github.baichuan.application.scaffold.dto.realm.RealmForm;
import com.github.baichuan.application.scaffold.dto.realm.RealmTableView;
import com.github.baichuan.mapping.BeanMapper;
import com.github.baichuan.web.dto.Pagination;
import com.github.baichuan.web.dto.PaginationCriteria;
import com.github.baichuan.web.dto.Result;
import com.github.baichuan.web.dto.SelectOption;
import com.github.baichuan.web.servlet.Restful;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@Tag(name = "应用域")
@RequestMapping("/realm")
public class RealmController {

    @Autowired
    private RealmService realmService;
    @Autowired
    private RealmTableView.Mapper tableMapper;

    @PostMapping("/query")
    @Operation(summary = "查询")
    public ResponseEntity<Pagination<RealmTableView>> query(@RequestBody PaginationCriteria paginationCriteria){
        Page<RealmTableView> page = realmService.query(paginationCriteria.pageable(RealmTableView.class))
                .map(x -> tableMapper.map(x));
        return ResponseEntity.ok(Pagination.of(page));
    }

    @Operation(summary = "表单数据")
    @GetMapping("/{id}")
    public ResponseEntity<RealmForm> get(@PathVariable("id") String id){
        Realm realm = realmService.find(id);
        RealmForm form = BeanMapper.map(realm, RealmForm.class);
        return ResponseEntity.ok(form);
    }

    @Operation(summary = "添加")
    @PostMapping
    public ResponseEntity<Result> add(@RequestBody @Valid RealmForm form){
        Result result = realmService.add(form);
        return Restful.created(result);
    }

    @Operation(summary = "修改")
    @PutMapping("/{id}")
    public ResponseEntity<Result> edit(@PathVariable("id") String id, @RequestBody @Valid RealmForm form){
        Result result = realmService.edit(id, form);
        return Restful.created(result);
    }

    @Operation(summary = "删除")
    @DeleteMapping("/{id}")
    public ResponseEntity<Result> remove(@PathVariable("id") String id){
        Result result = realmService.remove(id);
        return Restful.response(result);
    }


    @Operation(summary = "获取选项列表")
    @GetMapping("/options")
    public ResponseEntity<List<SelectOption>> options(){
        List<SelectOption> items = realmService.findAll().stream()
                .map(x -> new SelectOption(x.getName(), x.getId()))
                .collect(Collectors.toList());
        return ResponseEntity.ok(items);
    }
}
